/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.admin.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;

import javax.validation.Valid;

import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.modules.admin.dto.WxFaultTypeDTO;
import org.springblade.modules.admin.entity.WxFaultCause;
import org.springblade.modules.system.entity.Tenant;
import org.springblade.modules.system.service.ITenantService;
import org.springframework.web.bind.annotation.*;
import org.springblade.modules.admin.entity.WxFaultType;
import org.springblade.modules.admin.service.IWxFaultTypeService;
import org.springblade.core.boot.ctrl.BladeController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 故障责任表 控制器
 *
 * @author ysq
 * @since 2025-06-27
 */
@RestController
@AllArgsConstructor
@RequestMapping("admin/wx/fault/type")
@Api(value = "故障责任", tags = "故障责任接口")
public class WxFaultTypeController extends BladeController {

	private final IWxFaultTypeService wxFaultTypeService;

	private final ITenantService tenantService;

	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入wxFaultType")
	public R<WxFaultType> detail(Long id) {
		WxFaultType detail = wxFaultTypeService.getById(id);
		return R.data(detail);
	}


	@GetMapping("/copy")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入wxFaultType")
	public R<Boolean> copy(Long id) {
		WxFaultType detail = wxFaultTypeService.getById(id);
		WxFaultType faultType = wxFaultTypeService.getOne(Wrappers.<WxFaultType>lambdaQuery().orderByDesc(WxFaultType::getSort).last(" limit 1"));
		if (faultType.getIsOther() == 1) {
			throw new ServiceException("其它类型不能复制...");
		}
		WxFaultType wxFaultType = new WxFaultType();
		wxFaultType.setName(detail.getName() + "-副本");
		wxFaultType.setSort(0);
		wxFaultType.setUserName(AuthUtil.getNickName());
		wxFaultType.setStatus(0);
		wxFaultType.setFromType(1);
		wxFaultTypeService.save(wxFaultType);
		return R.data(true);
	}

	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入wxFaultType")
	public R submit(@Valid @RequestBody WxFaultType wxFaultType) {
		if (wxFaultType.getId() == null && (Convert.toStr(wxFaultType.getName(), "").equals("其它") || Convert.toStr(wxFaultType.getName(), "").equals("其他"))) {
			throw new ServiceException("不能新增其它故障责任");
		}

		if (wxFaultType.getSort() != null) {
			List<WxFaultType> typeList = wxFaultTypeService.list(Wrappers.<WxFaultType>lambdaQuery().eq(WxFaultType::getSort, wxFaultType.getSort()));
			List<WxFaultType> faultTypes = typeList.stream().filter(o -> !o.getId().equals(Convert.toLong(wxFaultType.getId(), -1L))).collect(Collectors.toList());
			if (faultTypes.size() > 0) {
				throw new ServiceException("故障责任序号不能相同");
			}
		}
		if (StrUtil.isNotEmpty(wxFaultType.getName())) {
			List<WxFaultType> typeList = wxFaultTypeService.list(Wrappers.<WxFaultType>lambdaQuery().eq(WxFaultType::getName, wxFaultType.getName()));
			List<WxFaultType> faultTypes = typeList.stream().filter(o -> !o.getId().equals(Convert.toLong(wxFaultType.getId(), -1L))).collect(Collectors.toList());
			if (faultTypes.size() > 0) {
				throw new ServiceException("故障责任不能相同");
			}
		}
		String tenantId = AuthUtil.getTenantId();
		if (tenantId.equals("000000")) {
			return submitAdmin(wxFaultType);
		}
		wxFaultType.setUserName(AuthUtil.getNickName());
		return R.status(wxFaultTypeService.saveOrUpdate(wxFaultType));
	}

	/**
	 * 000000租户的操作
	 *
	 * @return
	 */
	private R submitAdmin(WxFaultType wxFaultType) {
		wxFaultType.setUserName(AuthUtil.getNickName());
		wxFaultTypeService.saveOrUpdate(wxFaultType);
		if (wxFaultType.getStatus() == 1) {
			List<String> tenantIds = tenantService.list().stream().map(Tenant::getTenantId).distinct().collect(Collectors.toList());
			tenantIds.remove("000000");
			tenantIds.clear();
			tenantIds.add("592800");
			for (String tenantId : tenantIds) {
				List<WxFaultType> list = new ArrayList<>(1);
				wxFaultType.setId(null);
				list.add(wxFaultType);
				wxFaultTypeService.saveTenantBatch(tenantId, list);
			}
		}
		return R.status(true);
	}

	@PostMapping("page")
	public R<Page<WxFaultType>> list(@RequestBody WxFaultTypeDTO wxFaultTypeDTO, @RequestBody Query query) {
		Page<WxFaultType> page = wxFaultTypeService.list(Condition.getPage(query), wxFaultTypeDTO);
		return R.data(page);
	}

}
